package auth

import (
	"context"
	"errors"
	"usercenter/internal/biz"
	"usercenter/internal/svc"
	"usercenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendVerificationCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendVerificationCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendVerificationCodeLogic {
	return &SendVerificationCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendVerificationCodeLogic) SendVerificationCode(req *types.VerificationCodeRequest) (resp *types.VerificationResponse, err error) {
	// 1. 参数校验
	if req.Email == "" {
		return nil, &biz.BizError{
			Code:    400,
			Message: "邮箱不能为空",
		}
	}

	// 2. 调用验证码管理器发送验证码
	err = l.svcCtx.VerificationMgr.GenerateVerificationCode(req.Email)
	if err != nil {
		// 根据错误类型返回不同的响应
		if errors.Is(err, context.DeadlineExceeded) {
			return nil, &biz.BizError{
				Code:    504,
				Message: "发送超时，请稍后再试",
			}
		} else if err.Error() == "操作过于频繁，请1分钟后再试" {
			return nil, &biz.BizError{
				Code:    429,
				Message: "操作过于频繁，请1分钟后再试",
			}
		}

		l.Logger.Errorf("发送验证码失败: %v", err)
		return nil, &biz.BizError{
			Code:    500,
			Message: "验证码发送失败，请稍后再试",
		}
	}

	// 3. 记录日志（生产环境建议记录到日志系统）
	l.Logger.Infof("验证码已发送至邮箱: %s", req.Email)

	// 4. 返回成功响应
	return &types.VerificationResponse{
		Code:    200,
		Message: "验证码已发送，请查收邮件",
	}, nil
}
